<template>
  <div class="default-main ba-table-box">
    <div class="block">
      <div class="table-block">
        <el-alert class="ba-table-alert"
                  v-if="baTable.table.remark"
                  :title="baTable.table.remark"
                  type="info"
                  show-icon />
        <!-- 表格顶部菜单 -->
        <TableHeader :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
                     :quick-search-placeholder="t('Quick search placeholder', { fields: '订单号' })">
          <template #shop>
            <el-select filterable
                       v-model="baTable.comSearch.form['shop_id']"
                       clearable>
              <el-option v-for="item in shop_arr"
                         :key="item.shop_id"
                         :label="item.shop_name"
                         :value="item.shop_id">
              </el-option>
            </el-select>
          </template>
        </TableHeader>

        <el-row style="margin: 10px 0;"
                :gutter="10">
          <el-col :span="1.5"
                  v-if="baTable.auth('export')">
            <el-button type="warning"
                       @click="exportExcelOperate"
                       :loading="state.buttonLoading">
              <Icon color="#ffffff"
                    name="el-icon-Position" />导出
            </el-button>
          </el-col>
          <el-col :span="1.5"
                  v-if="baTable.auth('uploadAdv')">
            <el-upload ref="upload"
                       class="upload-demo"
                       action=""
                       :show-file-list="false"
                       @change="onUpload"
                       :auto-upload="false">
              <template #trigger>
                <el-button type="primary">上传广告消耗</el-button>
              </template>
              <el-link style="color: #ffffff;"
                       :href="`${baseUrl}/storage/system/advaccount.xls`"
                       :underline="false">
                <el-button type="warning"
                           style="margin-left: 10px;vertical-align: initial;">
                  下载广告消耗模板
                </el-button>
              </el-link>
            </el-upload>
          </el-col>
        </el-row>
        <Table show-summary
               :summary-method="getSummaries"></Table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, provide, onBeforeMount } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import baTableClass from '/@/utils/baTable'
// import PopupForm from './popupForm.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import { baTableApi, fileDownload } from '/@/api/common'
import { fileUpload, exportExcel } from '/@/api/backend/advertisement/advertising'
import Cookies from 'js-cookie'
import { useI18n } from 'vue-i18n'
import { getShopList } from '/@/api/backend/common'
import { getUrl } from '/@/utils/axios'

defineOptions({
    name: 'advertisement/advertising',
})
const { t } = useI18n()
const baseUrl = getUrl()
const state: {
    buttonLoading: boolean
} = reactive({
    buttonLoading: false
})
const shop_arr = ref([] as any[])
const baTable = new baTableClass(
    new baTableApi('/advertisement/advertising/'),
    {
        column: [
            {
                label: '店铺',
                prop:  'shop_id',
                operator: 'LIKE', 
                comSearchRender:'slot',
                comSearchSlotName: 'shop',
                show: false
            },
            {
                label: '运营',
                prop: 'admin_id',
                align: 'center',
                comSearchRender: 'remoteSelect',
                remote: {
                    pk: 'id',
                    field: 'nickname',
                    remoteUrl: '/advertisement/advaccount/OperationsList',
                    params: { select: true },
                },
                show: false
            },
            {   
                label: '广告账户', 
                prop: 'advertiser_id', 
                align: 'center',
                operator: false,
                operatorPlaceholder: '请输入广告账户'
            },
            { 
                label: '添加时间', 
                prop: 'stat_time_day', 
                align: 'center', 
                render: 'datetime', 
                sortable: 'custom', 
                operator: 'RANGE',
                show: false
            },
            {  
                label: '花费', 
                prop: 'spend', 
                align: 'center',
                operator: false
            },
            {   
                label: '广告名称', 
                prop: 'advertiser_name', 
                align: 'center',
                operator: false,
                show: false,
            },
            {   
                label: '消耗时间(美国日期)', 
                prop: 'stat_time_day', 
                align: 'center',
                operator: false
            },
            {   
                label: '归属人', 
                prop: 'admin_name', 
                align: 'center',
                operator: false
            },
            {   
                label: '店铺', 
                prop: 'shop_name', 
                align: 'center',
                operator: false
            },
        ],
        dblClickNotEditColumn: ['all']
    },
    {
        defaultItems: {
            status: '1',
        }
    }
)

provide('baTable', baTable)

baTable.mount()
baTable.getIndex()

const getSummaries = (param:any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column:any, index:any) => {
    const key = column.columnKey
    switch(key){
        case 'advertiser_id':
            sums[index] = `总计: ${String(baTable.table.total)}条`
            break
        case 'spend':
            sums[index] = `${baTable.table.extend?.spend_total}`
            break
        default:
            sums[index] = ''
    }
  })
  return sums
}

const onUpload = (file:any) => {
    let fd = new FormData()
    fd.append('file', file.raw)
    fileUpload(fd).then((res) => {
        if (res.code == 200) {
            ElMessage ({
                type: 'success',
                message: res.msg,
            })
        } else {
            ElMessage ({
                type: 'error',
                message: '上传失败',
            })
        }
    })
}

const exportExcelOperate = () => {
    state.buttonLoading = true
    baTable.table.loading = true
    ElMessageBox.confirm(
        '是否确认导出所有数据项?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        type keymaps = {
            [key: string]: string | number
        }
        const obj:keymaps = {}
        baTable.table.filter?.search!.forEach(v => {
            obj[v.field] = v.val
        }) || []
        exportExcel('post', obj).then(response => {
            fileDownload(response, Cookies.get('filename') || 'file.xlsx')
        }).catch(err => {
            state.buttonLoading = false
            baTable.table.loading = false
        }).finally(() => { 
            state.buttonLoading = false
            baTable.table.loading = false
        })
        state.buttonLoading = false
        baTable.table.loading = false
    }).catch(() => {
        state.buttonLoading = false
        baTable.table.loading = false
    })
}

const getShopArr = () => {
    getShopList().then(res => {
        if(res.data && res.data.list.length) {
            shop_arr.value = res.data.list
        }
    })
}

onBeforeMount(async () => {
    getShopArr()
})
</script>

<style scoped lang="scss">
</style>
